package com.joeyzh.rfid

import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import com.joey.ui.general.OnActionListener
import java.util.regex.Pattern

/**
 * Create by Joey  2019-3-19
 * @author Joey
 *
 * RFID功能监听
 */
class RfidReceiver : BroadcastReceiver() {
    companion object {
        const val AUTH_ACTION_LOAD = "com.auth.ACTION_LOAD"
        const val AUTH_ACTION_FIND = "com.auth.ACTION_FIND"
        const val AUTH_ACTION_SIGN = "com.auth.ACTION_SIGN"
        const val START_ACTION_CLS_NAME = "com.joeyzh.auth.CardBroadCastReceiver"
        const val DEFAULT_ACTION_TAG = "DEFAULT"


        /**
         * 用来标记触发操作的
         */
        private var ActionTag: String? = null

        fun wakeUpRfid(context: Context?, tag: String?) {
            ActionTag = tag!!
            var tagValue: String? = null

            if (isContainChinese(tag)){
                tagValue = tag;
            }else{
                tagValue = DEFAULT_ACTION_TAG;
            }
            context!!.sendBroadcast(Intent(RfidReceiver.AUTH_ACTION_LOAD).setComponent(ComponentName(context!!.getPackageName(), START_ACTION_CLS_NAME)).putExtra("title", tagValue))
        }

        /**
         * 判断字符串中是否包含中文
         * @param str
         * 待校验字符串
         * @return 是否为中文
         * @warn 不能校验是否为中文标点符号
         */
        fun isContainChinese(str: String): Boolean {
            val p = Pattern.compile("[\u4e00-\u9fa5]")
            val m = p.matcher(str)
            return m.find()
        }

        fun wakeUpRfid(context: Context?) {
            ActionTag = DEFAULT_ACTION_TAG
            context!!.sendBroadcast(Intent(RfidReceiver.AUTH_ACTION_LOAD).setComponent(ComponentName(context!!.getPackageName(), START_ACTION_CLS_NAME)).putExtra("title", ActionTag))
        }

    }

    override fun onReceive(context: Context?, intent: Intent?) {
        if (AUTH_ACTION_FIND == intent!!.action) {
            val bundle = intent!!.extras
            bundle.putString("ActionTag", ActionTag)
            if (context is OnActionListener) {
                context.onAction(AUTH_ACTION_FIND, bundle)
            }
        }
    }


}